<template>
  <div>
    <div class="search_box search_head" style="margin-bottom: 12px">
      <el-radio-group v-model="type" @change="handleGroup(type)">
        <el-radio-button :label="1">充值订单流水</el-radio-button>
        <el-radio-button :label="2">用户注册流水</el-radio-button>
      </el-radio-group>
    </div>
    <div class="search_box">
      <el-form
        :inline="true"
        ref="ruleFormRef"
        :model="formData"
        :label-width="70"
      >
        <el-form-item>
          <selectDate
            ref="dateRef"
            type="daterange"
            @returnTime="returnTime"
            :utcType="true"
          />
        </el-form-item>
        <el-form-item>
          <selectMultiple
            ref="selectUserRef"
            @selectChange="selectUser"
            :placehText="'优化师'"
            :options="userOptions"
          />
        </el-form-item>
        <el-form-item>
          <t-select
            placeholder="请选择推广链接"
            v-model="formData.promotionIds"
            :optionSource="pomotionIdOptions"
            labelCustom="label"
            valueCustom="value"
            @current-change="currentSelectChange"
            isShowPagination
            multiple
            collapse-tags
            collapse-tags-tooltip
            :paginationOption="paginationOption"
          />
        </el-form-item>
        <el-form-item>
          <selectMultiple
            ref="selectPomotionRef"
            @selectChange="selectPomotion"
            :placehText="'推广平台'"
            :options="[{ label: '巨量2.0', value: 'tt2' }]"
          />
        </el-form-item>
        <el-form-item>
          <selectMultiple
            ref="selectBackRef"
            @selectChange="selectBack"
            :placehText="'回传状态'"
            :options="selectBackOptions"
          />
        </el-form-item>
        <el-form-item>
          <el-input v-model="formData.uid" placeholder="用户Uid" clearable />
        </el-form-item>
        <template v-if="type == 2">
          <el-form-item>
            <selectMultiple
              ref="selectStatusRef"
              @selectChange="selectStatus"
              :placehText="'转化类型'"
              :options="statusOptions"
            />
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="formData.registerType"
              placeholder="是否回流"
              clearable
            >
              <el-option label="首次注册" :value="0" />
              <el-option label="回流注册" :value="1" />
            </el-select>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item>
            <el-input
              v-model="formData.payTimes"
              placeholder="充值次数"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="formData.greaterThanPayAmount"
              placeholder="充值金额大于等于"
              clearable
            />
          </el-form-item>
        </template>

        <el-form-item>
          <el-input
            v-model="formData.adId"
            placeholder="广告计划ID"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-input
            v-model="formData.advertiserId"
            placeholder="广告账户ID"
            clearable
          />
        </el-form-item>

        <el-form-item
          v-auth-all="[
            'api:agent:manual:orderSearch',
            'api:agent:manual:registSearch',
          ]"
        >
          <el-button type="primary" @click="getList(1)"> 查 询 </el-button>
          <el-button @click="resetList"> 重 置 </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table_box_wrapper">
      <div class="search_box" style="padding: 10px 10px 0" v-if="type == 1">
        <el-button
          type="primary"
          @click="batchManual"
          v-auth="'api:agent:manual:batch'"
        >
          <el-icon style="margin-right: 5px">
            <EditPen />
          </el-icon>
          批量补单
        </el-button>
      </div>
      <custom-table
        ref="tableRef"
        :loading="loading"
        :columns="columns"
        :tableData="tableData"
        :pageObj="pageObj"
        @sizechange="sizechange"
        @currentChange="currentChange"
        class="table_box"
        :isCustomHead="true"
      >
        <template #callbackStatus="{ scope }">
          <el-tag
            v-if="scope.row?.callbackStatus"
            :type="typeStatus(scope.row?.callbackStatus)"
          >
            {{ statusText[scope.row?.callbackStatus] }}
          </el-tag>
        </template>
        <template #registerType="{ scope }">
          <span v-if="scope.row?.callbackStatus">
            {{ !scope.row?.registerType ? "首次注册" : "回流注册" }}</span
          >
        </template>
        <template #convertType="{ scope }">
          <el-tag
            v-if="scope.row?.convertType"
            :type="
              scope.row?.convertType == 1
                ? 'danger'
                : scope.row?.convertType == 2
                ? ''
                : 'success'
            "
          >
            {{
              scope.row?.convertType == 1
                ? "未付费"
                : scope.row?.convertType == 2
                ? "手动转化"
                : "已付费"
            }}
          </el-tag>
        </template>
        <template #payTime="{ scope }">
          <span v-if="scope.row?.payTime">
            {{ moment(scope.row?.payTime + "Z").format("YYYY-MM-DD HH:mm:ss") }}
          </span>
        </template>
        <template #convertTime="{ scope }">
          <span v-if="scope.row?.convertTime">
            {{
              moment(scope.row?.convertTime + "Z").format("YYYY-MM-DD HH:mm:ss")
            }}
          </span>
        </template>
        <template #registerTime="{ scope }">
          <span v-if="scope.row?.registerTime">
            {{
              moment(scope.row?.registerTime + "Z").format(
                "YYYY-MM-DD HH:mm:ss"
              )
            }}
          </span>
        </template>
        <template #callbackTime="{ scope }">
          <span v-if="scope.row?.callbackTime">
            {{
              moment(scope.row?.callbackTime + "Z").format(
                "YYYY-MM-DD HH:mm:ss"
              )
            }}
          </span>
        </template>

        <template #operator="{ scope }">
          <el-button
            v-auth="'api:agent:manual:orderRepair'"
            type="primary"
            v-if="type === 1 && isCallbackStatus(scope.row?.callbackStatus)"
            @click.stop="handleManual(scope.row, '补单')"
            >回传补单</el-button
          >
          <el-button
            v-auth="'api:agent:manual:registRepair'"
            type="success"
            v-if="type === 2 && scope.row?.convertType === 1"
            @click.stop="handleManual(scope.row, '转化')"
            >手动转化</el-button
          >
        </template>
      </custom-table>
    </div>

    <!-- 批量补单 -->
    <batchDialog ref="manualRef" @success="getList(1)" />
  </div>
</template>

<script setup lang="ts">
import { EditPen } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive, onMounted, nextTick, h } from "vue";
import customTable from "@/components/CustomTable/index.vue";
import selectDate from "@/components/SeleteDate/index.vue";
import batchDialog from "./components/batchDialog.vue";
import { getUserList } from "@/api/userManage/index";
import { promotionSearchList } from "@/api/promotionLink/index";
import {
  payOrderList,
  registeredList,
  payorderManual,
  orderCount,
} from "@/api/echoRecord/index";
import moment from "moment";

const manualRef = ref();
const tableRef = ref();
const loading = ref<boolean>(false);
const type = ref<number>(1);
let startT: number = new Date().getTime() - 3600000 * 24 * 6;
let endT: number = new Date().getTime() + 3600000 * 24;
const form = reactive({
  pageNo: 1,
  pageSize: 10,
  start: moment(startT).startOf("day").utc().format("YYYY-MM-DDTHH:mm:ss"),
  end: moment(endT).startOf("day").utc().format("YYYY-MM-DDTHH:mm:ss"),
  optimizerIds: [], // 优化师Ids
  promotionIds: [], // 推广链接Ids
  platforms: [], // 推广平台
  callbackStatus: [], // 回传状态
  uid: "", // 用户 uid
  payTimes: undefined, // 充值次数
  greaterThanPayAmount: undefined, // 充值金额
  adId: "", // 广告计划Id
  advertiserId: "", // 广告账户id
  convertTypes: [], // 转化类型
  registerType: undefined, // 是否回流注册用户 0 - 否，1 - 是
  selectNums: undefined, // 数量
});
const formData = ref(Object.assign({}, form));
const valueTime = ref<any>("");
const tableData = ref<Array<any>>([]);
const userOptions = ref<Array<any>>([]); // 优化师
const pomotionIdOptions = ref<Array<any>>([]); // 推广平台
const statusOptions = reactive([
  // 转化类型
  { label: "未付费", value: 1 },
  { label: "手动转化", value: 2 },
  { label: "已付费", value: 3 },
]);
let statusText = [
  "等待处理",
  "处理中",
  "回传成功",
  "回传失败",
  "手动补单成功",
  "批量补单成功",
  "不符合配置条件",
  "不符合间隔回传",
  "等待必要参数",
  "缺失必要参数",
  "未匹配监测记录",
  "延迟重试",
];
const selectBackOptions = ref([
  // 回传状态
  { label: statusText[0], value: 0 },
  { label: statusText[1], value: 1 },
  { label: statusText[2], value: 2 },
  { label: statusText[3], value: 3 }, //  充值显示
  { label: statusText[4], value: 4 },
  // { label: statusText[5], value: 5 },
  { label: statusText[6], value: 6 }, // 充值显示
  { label: statusText[7], value: 7 }, // 充值显示
  // { label: statusText[8], value: 8 },
  // { label: statusText[9], value: 9 },
  { label: statusText[10], value: 10 },
  // { label: statusText[11], value: 11 },
  // 未付费
]);

const selectUserRef = ref();
const selectPomotionRef = ref();
const selectBackRef = ref();
const selectStatusRef = ref();
const dateRef = ref();

interface modelPage {
  pageNo: number;
  pageSize: number;
  total: number;
}
const pageObj = reactive<modelPage>({
  pageNo: 1,
  pageSize: 10,
  total: 0,
});

const paginationOption = ref({
  pageSize: 6, // 每页显示条数
  currentPage: 1, // 当前页
  pagerCount: 5, // 按钮数，超过时会折叠
  total: 0, // 总条数
});

// 回传状态
const typeStatus = (val: any) => {
  if (val === 2 || val === 4 || val === 5) {
    return "success";
  } else if (
    val === 3 ||
    val === 6 ||
    val === 7 ||
    val === 9 ||
    val === 10 ||
    val === 11
  ) {
    return "danger";
  } else {
    return "warning";
  }
};

const columns = ref([
  { label: "ID", prop: "id", minWidth: 60, fixed: "left" },
  { label: "用户UId", prop: "memberId", minWidth: 90, fixed: "left" },
  // { label: "分销商", prop: "miniApp", slotName: "miniApp", minWidth: 120 },
  { label: "优化师", prop: "optimizerName", minWidth: 100 },
  { label: "推广平台", prop: "platform", minWidth: 90 },
  { label: "推广名称 ", prop: "linkName", minWidth: 140 },
  { label: "广告账号", prop: "advertiserId", minWidth: 155 },
  { label: "广告计划", prop: "adId", minWidth: 175 },
  {
    label: "回传状态",
    prop: "callbackStatus",
    slotName: "callbackStatus",
    minWidth: 130,
  },
  { label: "回传备注", prop: "callbackRemark", minWidth: 125 },
  // 订单
  { label: "商品类型", prop: "payItemName", minWidth: 100 },
  { label: "充值金额(分)", prop: "payAmount", minWidth: 110 },
  { label: "第几次充值", prop: "payTimes", minWidth: 100 },
  { label: "充值时间", prop: "payTime", slotName: "payTime", minWidth: 155 },
  // 注册
  {
    label: "转化类型",
    prop: "convertType",
    slotName: "convertType",
    minWidth: 100,
    hidden: true,
  },
  {
    label: "转化时间",
    prop: "convertTime",
    slotName: "convertTime",
    minWidth: 155,
    hidden: true,
  },
  //
  {
    label: "注册时间",
    prop: "registerTime",
    slotName: "registerTime",
    minWidth: 155,
  },
  {
    label: "注册类型",
    prop: "registerType",
    minWidth: 100,
    slotName: "registerType",
  },
  { label: "重试次数", prop: "callbackRetryTimes", minWidth: 80 },
  {
    label: "回传时间",
    prop: "callbackTime",
    slotName: "callbackTime",
    minWidth: 155,
  },
  {
    label: "操作",
    prop: "operator",
    slotName: "operator",
    width: 120,
    fixed: "right",
  },
]);

const isCallbackStatus = (val: number) => {
  return val == 3 || val == 6 || val == 7;
};

// 补单 转化
const handleManual = (val: Record<string, any>, str: string) => {
  if (str === "补单") {
    ElMessageBox.confirm(`确定对订单id（${val.id}）进行回传补单吗?`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      payorderManual(val?.id).then(() => {
        ElMessage.success("补单成功");
        getList(1);
      });
    });
  } else {
    manualRef.value.showDialog(val, "转化");
  }
};

// 优化师
const selectUser = (val: any) => {
  formData.value.optimizerIds = val;
};

// 推广平台
const selectPomotion = (val: any) => {
  formData.value.platforms = val;
};

// 回传状态
const selectBack = (val: any) => {
  formData.value.callbackStatus = val;
};

// 转化类型
const selectStatus = (val: any) => {
  formData.value.convertTypes = val;
};

// 重置
const resetList = () => {
  formData.value = Object.assign(formData.value, form);

  if (type.value == 2) {
    selectStatusRef.value.multipleData = [];
  }
  selectUserRef.value.multipleData =
    selectPomotionRef.value.multipleData =
    selectBackRef.value.multipleData =
      [];
  dateRef.value.dateValue = [form.start, form.end];
  getList(1);
};

// 切换充值 / 注册
const handleGroup = (val: number | string) => {
  if (val === 1) {
    formData.value.payTimes = undefined;
    formData.value.greaterThanPayAmount = undefined;
  } else {
    formData.value.convertTypes = [];
    formData.value.registerType = undefined;
  }
  tableRef.value.columnsData = columns.value.map((item: any) => {
    // 根据type（1 、 2）类型，显示影藏列
    if (
      val === 1 &&
      (item.prop === "convertType" || item.prop === "convertTime")
    ) {
      item.hidden = true;
    } else if (
      val === 2 &&
      (item.prop === "payItemName" ||
        item.prop === "payAmount" ||
        item.prop === "payTimes" ||
        item.prop === "payTime")
    ) {
      item.hidden = true;
    } else {
      item.hidden = false;
    }
    return item;
  });
  // console.log("tableRef.value.columnsData-----", tableRef.value.columnsData);

  getList(1);
};

const getList = (val = 0) => {
  // if (!val) {
  //   formData.value.pageNo = pageObj.pageNo;
  //   formData.value.pageSize = pageObj.pageSize;
  // } else {
  //   formData.value.pageNo = pageObj.pageNo = val === 1 ? val : 1;
  //   formData.value.pageSize = pageObj.pageSize =
  //     val === 1 ? 10 : pageObj.pageSize;
  // }
  formData.value.pageNo = pageObj.pageNo;
  formData.value.pageSize = pageObj.pageSize;

  formData.value.greaterThanPayAmount =
    formData.value.greaterThanPayAmount || undefined;
  formData.value.payTimes = formData.value.payTimes || undefined;
  formData.value.registerType =
    !formData.value.registerType && formData.value.registerType !== 0
      ? undefined
      : formData.value.registerType;
  loading.value = true;
  let Url;
  if (type.value == 1) {
    Url = payOrderList;
  } else {
    Url = registeredList;
  }
  Url(formData.value)
    .then((res: Record<string, any>) => {
      tableData.value = res.data;
      pageObj.total = Number(res?.total);
      loading.value = true;
    })
    .finally(() => {
      loading.value = false;
    });
};

const currentChange = (val: number) => {
  pageObj.pageNo = val;
  getList();
};

const sizechange = (val: number) => {
  pageObj.pageSize = val;
  getList(2);
};

// 获取小程序
const getUserSearch = () => {
  getUserList({ currentPage: 1, pageSize: 1000 }).then(
    (res: Record<string, any>) => {
      userOptions.value = res.data?.list.map((res: Record<string, any>) => {
        return {
          label: `${res.name}`,
          value: res?.id.toString(),
        };
      });
    }
  );
};

// 切换推广链接分页
const currentSelectChange = (val: any) => {
  getPromotionList(val);
};

// 获取剧集
const getPromotionList = (val = 0) => {
  let params = {
    pageNo: val || paginationOption.value.currentPage,
    pageSize: paginationOption.value.pageSize,
  };
  promotionSearchList(params).then((res: Record<string, any>) => {
    pomotionIdOptions.value = res.data.map((item: Record<string, any>) => {
      return {
        label: `id：${item.id} - ${item.linkName}`,
        value: item?.id,
      };
    });
    paginationOption.value.total = res.total;
  });
};

// 返回时间
const returnTime = (val: any) => {
  valueTime.value = val;
  formData.value.start = valueTime.value[0];
  formData.value.end = valueTime.value[1];
};

// 批量补单
const batchManual = async () => {
  let num: any = await orderCountList();
  formData.value.selectNums = num;
  manualRef.value.showDialog(formData.value, "补单");
};

// 获取补单数
const orderCountList = () => {
  return orderCount(formData.value).then((res) => {
    return res;
  });
};

onMounted(() => {
  getList();
  getUserSearch();
  getPromotionList();
});
</script>

<style lang="scss" scoped>
.search_head {
  display: flex;
  align-items: center;
}

.table_box_wrapper {
  margin-top: 15px;
  background-color: #fff;
}

.table_box {
  padding: 10px;
  border-radius: 4px;

  .movie_box {
    display: flex;
    align-items: center;

    img {
      width: 72px;
      height: 108px;
      margin-right: 8px;
    }

    span {
      flex: 1;
    }
  }
}
</style>
